﻿
function CallServer(pUrl, pData, pFuncNameSuccess, pType, pAsync, pdataType, pcontenType) {
    pType = pType;
    pAsync = pAsync;
    $.ajax({
        url: pUrl,
        async: pAsync,
        cache: false,
        type: pType,
        data: pData,
        contentType: pcontenType,
        dataType: pdataType,
        success: pFuncNameSuccess,
        error: function (XMLHttpRequest, textStatus, errorThrown) {

            return;
        }
    });
}

function Login() {
    var sName = $('#txtName').val();
    var sPW = $('#txtPassWord').val();
    if (sName =='' ||sName == null) {
        return;
    }
    var param = {'Name': sName , 'PW': sPW };
    CallServer('WebService.asmx/Login', param, LoginCallBack, 'POST', true, 'json');
        
}

function LoginCallBack(data) {
    //var sResult = JSON.parse(data); //Dung webservice thi k parse
     if (data.Result == true) {
        $.mobile.showPageLoadingMsg('z', 'Xin vui lòng chờ', true);
        var s = window.location.href;
        var sUrl = s.indexOf('ReturnUrl') == -1 ? 'Devices.aspx' : getUrlVars()["ReturnUrl"];
        window.location.href = sUrl;
    } else {

        $('#lblError').html('Mật khẩu hoặc tên người dùng không đúng!');
    }
}

function Logout() {
    CallServer('WebService.asmx/Logout', '', LogoutCallBack, 'POST', true, 'json');
}

function LogoutCallBack(data) {
   // $.mobile.changePage('default.aspx', { transition: 'slide' });
    window.location.href = 'default.aspx';
 }

 function CreateGrid() {
     var nHeight = $(window).height() - 41; //$('#header').height(): 41
     
     if (bWindowPhone)
     {
        nHeight = ($(document).height() > $(window).height() ? $(document).height() : $(window).height()) + nHDelta;
     }
    var nWidth = nW;
    jQuery('#grid').jqGrid({
        hoverrows: false,
        viewrecords: true,
        jsonReader: { "repeatitems": false, "subgrid": { "repeatitems": false} },
        xmlReader: { "repeatitems": false, "subgrid": { "repeatitems": false} },
        gridview: true,
        url: 'Services/GetDataGrid.ashx',
        rowNum: 20,
        rowList: [20, 30, 40],
        //sortname: 'ID',
        datatype: 'json',
        //scrollPaging: true,
        //shrinkToFit: false,
        //iScroll: { "hScrollbar": false, "vScrollbar": false },
        iScroll: { "hideScrollbar": true }, //load scroll if need
        rownumbers: true,
        gridComplete: function () {
            AlertSpeed('grid');
        },
        loadComplete: function (data) {
            if (data == null) {
                window.location.href = 'default.aspx';
            }
        },
        loadError: function (xhr, status, error) {
            window.location.href = 'default.aspx';
        },
        
        colModel: [
            { name: 'ID', index: 'ID', label: 'Thiết bị', width: 50},
            { name: 'Plate', index: 'Plate', label: 'Số xe', width: 50},
            { name: 'Speed', index: 'Speed', label: 'Vận tốc', width: 40},
            { name: 'Status', index: 'Status', label: 'Trạng Thái', hidden: true},
            { name: 'Time', index: 'Time', label: 'Thời gian', width: 55},
            { name: 'Location', index: 'Location', label: 'Địa chỉ', width: 150}
        ],
        width: nWidth,
        height: nHeight, 
        postData: { "oper": "grid" },
        prmNames: { "page": "page", "rows": "rows", "sort": "sidx", "order": "sord", "search": "_search", "nd": "nd", "id": "id", "filter": "filters", "searchField": "searchField", "searchOper": "searchOper", "searchString": "searchString", "oper": "oper", "query": "grid", "addoper": "add", "editoper": "edit", "deloper": "del", "excel": "excel", "subgrid": "subgrid", "totalrows": "totalrows", "autocomplete": "autocmpl" }, "loadError": function (xhr, status, err) { try { jQuery.jgrid.info_dialog(jQuery.jgrid.errors.errcap, '<div class="ui-state-error">' + xhr.responseText + '</div>', jQuery.jgrid.edit.bClose, { buttonalign: 'right' }); } catch (e) { alert(xhr.responseText); } },
        pager: '#pager'
    });
    //jQuery('#grid').jqGrid('filterToolbar', { "stringResult": true });
}

function AlertSpeed(tableName) {
    var data = jQuery('#' + tableName).jqGrid('getRowData');
    for (var i = 0; i < data.length; i++) {
        switch (data[i].Status) {
        //Mat tin hieu
        case "0": 
            {
                jQuery('#' + tableName).jqGrid('setRowData', (i + 1), {Location : data[i].Location.replace('hw=', 'h=' + nH + '&w=' + nW)});
                break;
            }
        //Mat GPS
        case "1":
            {
                jQuery('#' + tableName).jqGrid('setRowData', (i + 1), { Location: data[i].Location.replace('hw=', 'h=' + nH + '&w=' + nW) }, {color: 'yellow' });
                break;
            }
            
        case "2": //Xe dung
            {
                jQuery('#' + tableName).jqGrid('setRowData', (i + 1), { Location: data[i].Location.replace('hw=', 'h=' + nH + '&w=' + nW) }, { color: 'red' });
                break;
            }
        case "3": //Xe dang chay
            {
                jQuery('#' + tableName).jqGrid('setRowData', (i + 1), { Location: data[i].Location.replace('hw=', 'h=' + nH + '&w=' + nW) }, { color: 'green' });
                break;
            }
        default:
        }
    
}

}

function Resize() {
    var nHeight = $(window).height() - $('#header').height() - nHDelta;
    if (bWindowPhone) {
        nHeight = $(document).height() + nHDelta;
    }
    var nWidth = $(window).width();
    jQuery('#grid').jqGrid('setGridHeight', nHeight);
    jQuery('#grid').jqGrid('setGridWidth', nWidth);
       
    //resizeJqGridWidth('grid','content', $(window).width()  );
}

function resizeJqGridWidth(grid_id, div_id, width) {
    $(window).bind('resize', function () {
        $('#' + grid_id).setGridWidth(width, false); //Back to original width
        $('#' + grid_id).setGridWidth($('#' + div_id).width(), true); //Resized to new width as per window
    }).trigger('resize');
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}